package com.ziru.ziru.controller;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.ziru.ziru.pojo.Tenant;
import com.ziru.ziru.service.TenantService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

@Controller
@Slf4j
@Api(tags = "用户管理接口")
public class TenantController {

    @Resource
    private TenantService tenantService;

    @RequestMapping("/login.do")
    @ApiOperation("用户登录")
    public String login(@ApiParam("用户实体类参数") Tenant tenant, HttpSession session){
        if(StringUtils.isBlank(tenant.getPhone()) || StringUtils.isBlank(tenant.getPassword()) ) {
            session.setAttribute("error", "登录失败");
            return "login.jsp";
        }
        Tenant user = tenantService.login(tenant, session);
        if (user == null){
            session.setAttribute("error", "账户不存在");
            return "login.jsp";
        }
        String pwd = user.getPassword();
        if (!pwd.equals(tenant.getPassword())){
            session.setAttribute("error", "密码错误");
            return "login.jsp";
        }
        session.setAttribute("name", user.getNickname());
        return "index.jsp";
    }

    @ApiOperation("退出登录")
    @RequestMapping("/logout.do")
    public String logout(HttpSession session){
        session.removeAttribute("name");
        session.invalidate();
        return "index.jsp";
    }

    @ApiOperation("用户注册")
   @RequestMapping("/register.do")
   public String register(Tenant tenant, Model model){
       System.out.println(tenant);
       int i = tenantService.Register(tenant);
       //存储在请求中
       model.addAttribute("res",i);
       return "register.jsp";
   }
}
